Named Routes: Parameter Substitution and URL Generation


Parameter substitution in named routes and generate URLs dynamically, including handling optional parameters and generating URLs in views and redirects.

// Define named routes with optional parameters
Route::get('post/{post}/comment/{comment?}', [CommentController::class, 'show'])
    ->name('post.comment');

// Generate URL with required and optional parameters
$url = route('post.comment', ['post' => 1, 'comment' => 5]);

// Generate URL with only required parameters
$url = route('post.comment', ['post' => 1]);

// Redirect to a named route with parameters
return redirect()->route('post.comment', ['post' => 1, 'comment' => 5]);

Route::get('post/{post}/comment/{comment?}', [CommentController::class, 'show'])->name('post.comment'): Defines a named route 'post.comment' with an optional {comment} parameter. If {comment} is not provided, the route will still be valid.

route('post.comment', ['post' => 1, 'comment' => 5]): Generates a URL for the 'post.comment' route with both required and optional parameters substituted.

route('post.comment', ['post' => 1]): Generates a URL for the 'post.comment' route with only the required parameter.

redirect()->route('post.comment', ['post' => 1, 'comment' => 5]): Redirects to the named route with specified parameters.

You Might Also Like

Monitor Command Execution with Output Control

Control and monitor the output of Artisan commands using Laravel's built-in methods. This allows you...

Use Lazy Eager Loading for Conditional Relationships

Load related models only when needed using lazy eager loading. This technique helps in optimizing qu...